package com.lovepick.http;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.lovepick.util.Constant;

public class GetOrderService extends Service
{
	private static final String TAG = "GetOrderService";
	public static String mRole = Constant.PASSENGER;
	private OrderThread mThread = null;

	@Override
	public void onCreate()
	{
		Log.i(TAG, "---order service create---");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	{
		Log.i(TAG, "---service start---");
		if (intent != null)
		{
			Bundle args = intent.getBundleExtra("bundle");
			if (args.containsKey(Constant.ARG_ROLE))
			{
				mRole = args.getString(Constant.ARG_ROLE);
			}
		}

		// 开启获取历史订单的线程
		mThread = new OrderThread();
		mThread.isRunning = true;
		mThread.start();

		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public IBinder onBind(Intent arg0)
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		Log.i(TAG, "order service destroy");
		if (mThread != null)
		{
			mThread.isRunning = false;
		}

		System.exit(0);
	}

	private class OrderThread extends Thread
	{
		private static final String THREAD_TAG = "OrderThread";
		public boolean isRunning = true;

		@Override
		public void run()
		{
			Log.i(THREAD_TAG, "---OrderThread start---");
			while (isRunning)
			{
				try
				{
					String url = Constant.HTTP_URL_ORDER_MANAGE + "/" + mRole;
					HttpHelper httpHelper = new HttpHelper();
					String result = httpHelper.doGet(url);
					result = result.replace("\\\"", "\"")		// \" --> "
							.replace("\"[", "[")				// "[ --> [
							.replace("]\"", "]")				// ]" --> ]
							.replace("\"points\":\"\"", "\"points\":[]");	// "points":"" --> points:":[]
					if (result.startsWith(Constant.JSON_ARRAY_START))
					{
						Intent intent = new Intent(Constant.ACTION_ORDER);
						Bundle bundle = new Bundle();
						bundle.putString(Constant.ARG_ORDER, result);
						intent.putExtra("bundle_order", bundle);
						sendBroadcast(intent);
					}

					Thread.sleep(6000);
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					Log.i(THREAD_TAG, e.getCause().toString());
					continue;
				}
			}
		}

	}

}
